
function buildNote(node){
    var multiRow = (node.notes == null?0:node.notes.length)+(node.dictionaries == null?0:1)>1;
    var idx = 1;
    var html = "";
    if(node.notes != null && node.notes.length>0){
        for(var n in node.notes){
            if(multiRow){
                html += idx+"、";
            }
            html += node.notes[n]+"<br>";
            idx ++;
        }
    }
    if(node.dictionaries != null && node.dictionaries.length>0){
        if(multiRow){
            html += idx+"、";
        }
        if(node.dictType != null && node.dictType != ''){
            html += "字典[<font color='#dc143c'>"+node.dictType+"</font>]说明：<br>";
        }else{
            html += "数据项说明：<br>";
        }
        html += "<div style=\"padding-left:5px;max-height:150px;overflow:auto;\">";
        for (var d in node.dictionaries) {
            var dict = node.dictionaries[d];
            html += "<div  class=\"module\">"+dict.value+":"+dict.label+"</div>";
        }
        html += "<div>";
    }
    node.note = html;
    if(node.subNodes != null){
        for (var k in node.subNodes){
            buildNote(node.subNodes[k])
        }
    }
}

function auth() {
    var orgNo = $("#orgNo");
    var account = $("#account");
    var password = $("#password");
    if(orgNo.val()==""){
        alert("组织编码不能为空！");
        orgNo.focus();
        return;
    }
    if(account.val()==""){
        alert("账号不能为空！");
        account.focus();
        return;
    }
    if(password.val()==""){
        alert("密码不能为空！");
        password.focus();
        return;
    }
    var env = $("#env").find("option:selected").attr("env").toLowerCase()
    var reqParam = {
        "env": env,
        "orgNo":orgNo.val(),
        "account": account.val(),
        "password": password.val()
    };
    $.ajax({
        type: "get",
        contentType: "json",
        data:reqParam,
        url:contextPath+"/api/authorize?"+new Date(),
        success:function(res){
            if(res.success){
                $("#accessToken").val(res.data["accessToken"]);
                 $("#jwt").val(res.data["jwt"]);
            }else{
                alert(res.message);
            }
        }
    });
}

function getTestData(){
    var envId = $("#env").val();
    var accessToken =$("#accessToken").val();
    var jwt =$("#jwt").val();
    var reqParam = {"appName":appName,"envId":envId,"apiId":apiId,"path":apiPath,"jwt":jwt,"accessToken":accessToken};

    var requestParams = $("#requestParams").val();
    if(requestParams!=undefined&&requestParams!=""){
        var parameters = [];
        var jsons = JSON.parse(requestParams);
        for(key in jsons) {
            parameters.push(key);
        }
        reqParam["parameters"] = parameters;
    }

    var requestBody = $("#requestBody").val();
    if(requestBody!=undefined&&requestBody!=""){
        var bodyFields = [];
        var jsons = JSON.parse(requestBody);
        for(key in jsons) {
            bodyFields.push(key);
        }
        reqParam["bodyFields"] = bodyFields;
    }

    $.ajax({
        type: "post",
        async: true,
        contentType: "application/json",
        dataType: 'json',
        data: JSON.stringify(reqParam),
        url:contextPath+"/api/test-data?ajaxTime="+new Date(),
        success: function(res){
            if(res.success==false){
                alert(res.message);
            }else{
                if(res.data.servletPath){
                    $("#servletPath").val(res.data.servletPath);
                }
                $("#requestHeaders").val(res.data.headers);
                $("#requestParams").val(res.data.params);
                $("#requestBody").val(res.data.body);
            }
        }
    });
}
var traceId = "";
function test(){
    $("#log").html("");
    $("#responseData").val("");
    var envId = $("#env").val();
    var basePath = $("#env").find("option:selected").attr("basePath").toLowerCase()
    var servletPath = $("#servletPath").val();
    var requestParams = $("#requestParams").val();
    var requestHeaders = $("#requestHeaders").val();
    var requestBody = $("#requestBody").val();
    var accessToken =$("#accessToken").val();
    var jwt =$("#jwt").val();
    var bodyData = {"apiId":apiId,"envId":envId,"jwt":jwt,"accessToken":accessToken,"basePath":basePath,"servletPath":servletPath,"requestHeaders":requestHeaders,"appName":appName,"requestMethod":requestMethod,"requestParams":requestParams,"requestBody":requestBody};
    $.ajax({
        type: "post",
        async: true,
        contentType: "application/json",
        dataType: 'json',
        data: JSON.stringify(bodyData),
        url:contextPath+"/api/test?ajaxTime="+new Date(),
        success: function(res){
            if(res.success){
                traceId = JSON.parse(res.data).traceId;
                $("#responseData").val(res.data);
            }else{
                $("#responseData").val(JSON.stringify(res));
                traceId = "";
            }
        }
    });
}

function clearRes() {
    $("#responseData").val("");
    $("#log").html("");
}
var unitTestMap = {};

/**
 * 获取单元测试列表
 * */
function getUnitTests() {
    $.ajax({
        type: "get",
        async: true,
        contentType: "application/x-www-form-urlencoded; charset=utf-8",
        data:{},
        url:contextPath+"/test/unit-tests/"+apiId+"?ajaxTime="+new Date(),
        success: function(res){
            var html = "";
            if(res.success==true){
                for(i=0;i<res.data.length;i++){
                    var unitTest = res.data[i];
                    unitTestMap[unitTest.id] = unitTest;
                    var time = dateFormat(new Date(unitTest.createDt));
                    html += "<tr id=\"tr-"+unitTest.id+"\" odd=\""+(i%2==0)+"\">";
                    html += "<td style=\"text-align:left;\">";
                    if(unitTest.joinPressureTest){
                        html += "<input type=\"checkbox\" onchange='joinPressureTest(this)' value=\""+unitTest.id+"\" checked/>";
                    }else{
                        html += "<input type=\"checkbox\" onchange='joinPressureTest(this)' value=\""+unitTest.id+"\"/>";
                    }
                    html += "<a style=\"cursor:pointer;\" onclick=\"fillTestData('"+unitTest.id+"')\">"+unitTest.name+"@"+time+"</a>" ;
                    html += "</td>";
                    html += "<td width=\"20\">";
                    html +="<a style=\"cursor:pointer;\" onclick=\"deleteUnitTest('"+unitTest.id+"')\">&#10005</a>";
                    html += "</td>";
                    html += "</tr>";
                }
            }
            $("#unitTests").html(html);
        }
    });
}

/**
 * 获取单元测试列表
 * */
function deleteUnitTest(id) {
    if(!confirm("你确定要删除吗？")){
        return;
    }
    $.ajax({
        type: "delete",
        async: true,
        contentType: "application/x-www-form-urlencoded; charset=utf-8",
        data:{},
        url:contextPath+"/test/unit-test/"+id+"?ajaxTime="+new Date(),
        success: function(res){
            if(res.success==true){
                $("#tr-"+id).remove();
            }else{
                alert(res.message);
            }
        }
    });
}

/**
 * 填充测试数据
 * */
function fillTestData(id) {
    var unitTest = unitTestMap[id];
    $("#requestHeaders").val(unitTest.headers);
    $("#requestParams").val(unitTest.params);
    $("#requestBody").val(unitTest.body);
    $("#responseData").val(unitTest.result);
}

/**
 * 保存单元测试
 */
function saveUnitTest(){
    var testName = $("#testName").val();
    if(testName==""){
        alert("请输入测试名再提交！");
        $("#testName").focus();
        return;
    }
    var path = $("#servletPath").val();;

    var responseData = $("#responseData").val();
    var reqParam = {"appName":appName,"apiId":apiId,"path":path,"method":requestMethod,"result":responseData,"name":testName};
    var requestParams = $("#requestParams").val();
    if(requestParams!=undefined&&requestParams!=""){
        reqParam["params"] = requestParams;
    }
    var requestBody = $("#requestBody").val();
    if(requestBody!=undefined&&requestBody!=""){
        reqParam["body"] = requestBody;
    }
    var requestHeaders = $("#requestHeaders").val();
    if(requestHeaders!=undefined&&requestHeaders!=""){
        reqParam["headers"] = requestHeaders;
    }
    $.ajax({
        type: "post",
        async: true,
        contentType:"application/json",
        data:JSON.stringify(reqParam),
        url:contextPath+"/test/unit-test?ajaxTime="+new Date(),
        success: function(res){
            if(res.success==true){
                getUnitTests();
                alert("保存成功！");
            }else{
                alert(res.message);
            }
        }
    });
}

function getTestLog() {
    var jwt =$("#jwt").val();
    $.ajax({
        type: "get",
        async: true,
        contentType:"application/json",
        headers:{"jwt":jwt},
        url:contextPath+"/test/log/"+traceId,
        success: function(res){
            if(res.success==true){
                var message = res.data.message.replaceAll("\n","<br/>").replaceAll("\n\t","<br/>");
                $("#log").html(message);
            }
        }
    });
}
function joinPressureTest(obj){
    $.ajax({
        type: "put",
        async: true,
        contentType: "application/x-www-form-urlencoded; charset=utf-8",
        url:contextPath+"/test/unit-test/"+obj.value+"/"+obj.checked+"?ajaxTime="+new Date(),
        success: function(res){
            if(res.success==false){
                alert("操作失败！");
                obj.checked = !checked;
            }
        }
    });
}

function copyUrl() {
    var input = document.getElementById("url");
    input.select(); // 选中文本
    document.execCommand("copy"); // 执行浏览器复制命令
    alert("复制成功");
}
